package com.ea.admin.service.impl;

import com.ea.admin.mapper.AdminAccountMapper;
import com.ea.admin.mapper.DeptInfoMapper;
import com.ea.admin.pojo.Enum.RoleCode;
import com.ea.admin.service.*;
import com.ea.common.report.ReportFeign;
import com.ea.common.report.pojo.param.GetStatsReportVoParam;
import com.ea.common.report.pojo.vo.StatsReportVo;
import com.ea.common.result.BizException;
import com.ea.common.result.ErrorCode;
import com.ea.common.result.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StatsServiceImpl implements StatsService {
    @Resource
    CompanyPermissionService companyPermissionService;
    @Resource
    DeptPermissionService deptPermissionService;
    @Resource
    PermissionService permissionService;
    @Resource
    DepartmentService departmentService;
    @Resource
    ReportFeign reportFeign;
    @Resource
    AdminAccountMapper adminAccountMapper;
    @Resource
    DeptInfoMapper deptInfoMapper;

    @Override
    public StatsReportVo getStatsReport(Long accountId, List<Long> companyIdList, List<Long> deptIdList, String startDate, String endDate) {
        // 查询用户权限
        PermissionServiceImpl.PermissionList checked = permissionService
                .checkAndRefreshPermissionList(companyIdList, deptIdList, accountId);
        companyIdList = checked.companyIdList;
        deptIdList = checked.deptIdList;

        // 查出所有下级单位
        Long adminRoleId = adminAccountMapper.selectById(accountId).getAdminRoleId();
        List<Long> queryCompanyIdList = companyPermissionService.getSubCompanyIdList(accountId, companyIdList);
        List<Long> queryDeptIdList;

        // 部门管理员对应部门查询,单位以上层级管理员赋予以下所有部门权限
        if(adminRoleId== RoleCode.DEPT_SUPER_ADMIN.getCode().longValue()||
                adminRoleId== RoleCode.DEPT_ADMIN.getCode().longValue()) {
            // 查出所有下级部门
            queryDeptIdList = deptPermissionService.getSubDepartmentIdList(accountId, companyIdList, deptIdList);
        }else{
            queryDeptIdList =deptInfoMapper.getAllByCompanyId(queryCompanyIdList);
        }

        Integer totalCount =0;
        if(queryDeptIdList!=null && !queryDeptIdList.isEmpty()){
            // 获取部门的总人数
            totalCount = departmentService.getTotalCount(queryDeptIdList);

        }

        if (startDate != null) {
            startDate = startDate + " 00:00:00";
        }
        if (endDate != null) {
            endDate = endDate + " 23:59:59";
        }

        Result<StatsReportVo> result = reportFeign.getStatsReport(new GetStatsReportVoParam(queryCompanyIdList, queryDeptIdList, totalCount, startDate, endDate));
        if (result == null || result.getData() == null || result.getCode() != ErrorCode.NO_ERROR.getCode()) {
            throw new BizException(ErrorCode.TPS_DOWNSTREAM_SERVICE_ERROR);
        }
        return result.getData();
    }
}
